package cn.lh.util;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.ECGenParameterSpec;

/**
 * @描述:
 * @版权: Copyright (c) 2022
 * @作者: linhong
 * @版本: 1.0.0
 * @创建时间: 2023/7/4
 */
public class ECCEncryptionDemo {

        public static void main(String[] args) throws Exception {
            // 添加BouncyCastle作为提供者
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            // 创建密钥对生成器
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
            ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1"); // 选择椭圆曲线类型
            keyPairGenerator.initialize(ecSpec);

            // 生成密钥对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();

            // 加密
            Cipher cipher = Cipher.getInstance("ECIES", "BC");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            String plaintext = "Hello, World!";
            byte[] ciphertext = cipher.doFinal(plaintext.getBytes());

            // 解密
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedText = cipher.doFinal(ciphertext);
            String decryptedString = new String(decryptedText);

            // 输出结果
            System.out.println("原始文本：" + plaintext);
            System.out.println("加密后的文本：" + new String(ciphertext));
            System.out.println("解密后的文本：" + decryptedString);
        }

}
